# -*- coding: utf-8 -*-

'''
Created on 8 nov. 2009

@author: vincent.vanghelle
'''

from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import ugettext_lazy as _
from django import forms
import re as regex
from captcha.fields import CaptchaField
from mmorganizer.users.models import CustomUserProfile
from mmorganizer.games.models import Game

class UserCreateForm(UserCreationForm):
    email = forms.EmailField(label=_("Email"), max_length=75,min_length= 3)
    captcha = CaptchaField()
    def clean_email(self):
        email = self.cleaned_data["email"]
        if (regex.match('(\w+@\w+(?:\.\w+)+)',email)==None):
            raise forms.ValidationError(_("The email is incorrect."))
        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(_("A user with that email already exists."))
    
    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
            profile = CustomUserProfile(user=user)
            #TODO jeu nullable?
            profile.game=Game.objects.get(pk=1)
            profile.save();
        return user